package com.cover;

public class Test {
    private boolean busy = false; // 定义 busy 变量
    private final Object lock = new Object(); // 定义锁对象

    public void runLoop() {
        while (true) {
            synchronized (lock) {
                while (!busy) { // 如果 busy 为 false，等待
                    try {
                        lock.wait(); // 进入等待状态，直到 busy 变为 true
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt(); // 恢复中断状态
                        System.out.println("Thread interrupted");
                        return;
                    }
                }
                // busy 为 true，执行循环内容
                System.out.println("Performing loop operation...");
                // 这里可以执行你的业务逻辑
            }

            // 模拟一些耗时操作
            try {
                Thread.sleep(1000); // 模拟处理
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                System.out.println("Thread interrupted during sleep");
                return;
            }
        }
    }

    // 方法用于修改 busy 的状态并通知等待线程
    public void setBusy(boolean busy) {
        synchronized (lock) {
            this.busy = busy; // 修改 busy 状态
            if (busy) {
                lock.notifyAll(); // 通知所有等待线程
            }
        }
    }

    public static void main(String[] args) {
        Test example = new Test();

        // 启动工作线程
        Thread worker = new Thread(example::runLoop);
        worker.start();

        // 主线程模拟 busy 状态的切换
        try {
            Thread.sleep(3000); // 等待 3 秒后设置 busy 为 true
            example.setBusy(true);

            Thread.sleep(5000); // 再等待 5 秒后设置 busy 为 false
            example.setBusy(false);

            Thread.sleep(3000); // 再等待 3 秒后设置 busy 为 true
            example.setBusy(true);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

    }

}
